import { defineStore } from 'pinia'

interface CartItem {
  id: string
  name: string
  price: number
  quantity: number
  image: string
}

interface CartState {
  items: CartItem[]
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    items: []
  }),
  
  getters: {
    cartItems: (state) => state.items,
    
    cartTotal: (state) => {
      return state.items.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    
    cartCount: (state) => {
      return state.items.reduce((count, item) => {
        return count + item.quantity
      }, 0)
    }
  },
  
  actions: {
    addToCart(item: Omit<CartItem, 'quantity'> & { quantity?: number }) {
      const existingItem = this.items.find(i => i.id === item.id)
      
      if (existingItem) {
        existingItem.quantity += item.quantity || 1
      } else {
        this.items.push({
          ...item,
          quantity: item.quantity || 1
        })
      }
      
      // 保存到本地存储
      this.saveToLocalStorage()
    },
    
    removeFromCart(itemId: string) {
      const index = this.items.findIndex(item => item.id === itemId)
      if (index !== -1) {
        this.items.splice(index, 1)
        this.saveToLocalStorage()
      }
    },
    
    updateQuantity(itemId: string, quantity: number) {
      const item = this.items.find(item => item.id === itemId)
      if (item) {
        item.quantity = quantity
        this.saveToLocalStorage()
      }
    },
    
    clearCart() {
      this.items = []
      this.saveToLocalStorage()
    },
    
    saveToLocalStorage() {
      localStorage.setItem('cart', JSON.stringify(this.items))
    },
    
    loadFromLocalStorage() {
      const storedCart = localStorage.getItem('cart')
      if (storedCart) {
        try {
          this.items = JSON.parse(storedCart)
        } catch (error) {
          console.error('Failed to parse cart data from localStorage', error)
          this.items = []
        }
      }
    }
  }
})